package com.zhongke.cotrun.controller.manager;

import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.zhongke.cotrun.common.annotation.SysLog;
import com.zhongke.cotrun.common.util.APIResponse;
import com.zhongke.cotrun.common.util.AddIntegralUtils;
import com.zhongke.cotrun.model.pojo.*;
import com.zhongke.cotrun.model.resultpackage.CodeMsg;
import com.zhongke.cotrun.service.*;
import com.zhongke.cotrun.shiro.sys.entity.SysUserEntity;
import com.zhongke.cotrun.shiro.sys.service.SysUserService;
import com.zhongke.cotrun.shiro.sys.shiro.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 用户需求信息
 * @Author: songjing
 * @Date: 2020-03-27
 * @Version: V1.0
 */
@Api(tags = "用户需求信息相关接口")
@RestController("needInfo")
@RequestMapping("/manager/needInfo")
@Validated
public class NeedInfoController {
    @Autowired
    AddIntegralUtils addIntegralUtils;
    @Autowired
    NeedInfoService needInfoService;
    @Autowired
    WxSysDictService wxSysDictService;
    @Autowired
    WxUserInfoService wxUserInfoService;
    @Autowired
    MessageService messageService;
    @Autowired
    CommonConfigService commonConfigService;
    @Autowired
    RegionService regionService;
    @Autowired
    UserInfoService userInfoService;
    @Autowired
    SysUserService sysUserService;

    @Autowired
    private SysMessageService sysMessageService;

    private static final String APPROVAL_PASS_TYPE = "DEMAND_APPROVAL_PASS"; //审核通过的字典type

    private static final String APPROVAL_REJECT_TYPE = "DEMAND_APPROVAL_REJECT"; //审核驳回的字典type

    @ApiOperation(value = "查看需求详情")
//    @SysLog(value = "查看需求详情", type = "需求")
    @RequiresPermissions("sys:demand:info")
    @GetMapping(value = {"/selectNeedInfoDetail"}, produces = "application/json;charset=utf-8")
    public APIResponse selectNeedInfoDetail(@NotNull(message = "需求id不能为空") Long id) {
        if (ShiroUtils.getUserId() == null)
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        NeedInfo needInfo = needInfoService.selectDetailById(id);
        if (needInfo != null) {
            setStateLabel(needInfo);
            setTypeLabel(needInfo);
            setRegionName(needInfo);
            setUserName(needInfo);
            setApprovalUserName(needInfo);
        }
        return APIResponse.returnSuccess(needInfo);
    }

    @ApiOperation(value = "查看所有需求信息（支持模糊搜索）")
//    @SysLog(value = "查看需求列表", type = "需求")
    @RequiresPermissions("sys:demand:list")
    @GetMapping(value = {"/selectAll"}, produces = "application/json;charset=utf-8")
    public APIResponse selectAll(String searchKey, String type, String technicalFieldId, String province, String city, String state, String endDateS, String endDateE,
                                 @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        if (ShiroUtils.getUserId() == null)
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        PageInfo page = needInfoService.selectAllByManager(type, technicalFieldId, province, city, searchKey, state, endDateS, endDateE, pageNum, pageSize);
        List list = page.getList();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                NeedInfo needInfo = (NeedInfo) list.get(i);
                setStateLabel(needInfo);
                setRegionName(needInfo);
                setUserName(needInfo);
            }
        }
        Map data = new HashMap();
        int count = needInfoService.queryUnApprovalCounts("0");
        data.put("count", count);
        data.put("data", page);
        return APIResponse.returnSuccess(data);

    }

    @ApiOperation(value = "编辑需求")
    @SysLog(value = "编辑需求", type = "需求")
    @RequiresPermissions("sys:demand:update")
    @PostMapping("/updateNeedInfo")
    public APIResponse updateNeedInfo(NeedInfo needInfo) {
        if (ShiroUtils.getUserId() == null ||
                needInfo == null || needInfo.getId() == null
                || StringUtil.isEmpty(needInfo.getTitle()) || StringUtil.isEmpty(needInfo.getType())
                || StringUtil.isEmpty(needInfo.getTechnicalFieldId()) || StringUtil.isEmpty(needInfo.getTechnicalFieldDesc())
                || StringUtil.isEmpty(needInfo.getNote()))
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        NeedInfo n = needInfoService.selectDetailById(needInfo.getId());
        if (!"3".equals(n.getState())) {
            needInfo.setUserInfoId(n.getUserInfoId());
            needInfo.setUpdateBy(ShiroUtils.getUserId());
            needInfo.setState("0");
            if (needInfoService.update(needInfo)) {
                return APIResponse.returnSuccess("编辑成功");
            } else {
                return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);
            }
        } else
            return APIResponse.returnFail(CodeMsg.DATA_EMPTY);
    }

    @ApiOperation(value = "删除需求")
    @SysLog(value = "删除需求", type = "需求")
    @RequiresPermissions("sys:demand:delete")
    @GetMapping(value = {"/deleteNeedInfo"}, produces = "application/json;charset=utf-8")
    public APIResponse deleteNeedInfo(@NotNull(message = "需求主键不能为空") String id) {
        if (ShiroUtils.getUserId() == null)
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        if (needInfoService.managerDelete(id, ShiroUtils.getUserId())) {
            return APIResponse.returnSuccess("删除成功");
        } else {
            return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);
        }
    }


    @ApiOperation(value = "下线需求")
    @SysLog(value = "下线需求", type = "需求")
    @RequiresPermissions("sys:demand:cancel")
    @GetMapping(value = {"/offlineNeedInfo"}, produces = "application/json;charset=utf-8")
    public APIResponse offlineNeedInfo(@NotNull(message = "需求主键不能为空") Long id) {
        if (ShiroUtils.getUserId() == null)
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        if (needInfoService.managerOffline(id, ShiroUtils.getUserId())) {
            return APIResponse.returnSuccess("下线成功");
        } else {
            return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);
        }
    }

    @ApiOperation(value = "审核需求")
    @SysLog(value = "审核需求", type = "需求")
    @RequiresPermissions("sys:demand:approval")
    @GetMapping(value = {"/checkNeedInfo"}, produces = "application/json;charset=utf-8")
    public APIResponse checkNeedInfo(@NotNull(message = "需求主键不能为空") Long id, @NotNull(message = "审核状态不能为空") String state, String remarks) {
        if (ShiroUtils.getUserId() == null)
            return APIResponse.returnFail(CodeMsg.BIND_ERROR);
        if ("2".equals(state) && StringUtils.isEmpty(remarks))
            return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);
        if (needInfoService.managerCheck(id, ShiroUtils.getUserId(), state, remarks)) {
            SysMessageEntity messageEntity = null;
            if ("2".equals(state)) {
                messageEntity = sysMessageService.saveSysMessage(APPROVAL_REJECT_TYPE, id, "demand");
            } else {
                messageEntity = sysMessageService.saveSysMessage(APPROVAL_PASS_TYPE, id, "demand");
            }
            return APIResponse.returnSuccess("审核成功");
        } else {
            return APIResponse.returnFail(CodeMsg.UPDATE_ERROR);
        }
    }
    //设置状态label
    private void setStateLabel(NeedInfo needInfo){
        String stateLable = wxSysDictService.getDictLabel(needInfo.getState(), "need_state", needInfo.getState());
        needInfo.setStateLabel(stateLable);
    }
    //设置类型label
    private void setTypeLabel(NeedInfo needInfo){
        String typeLable = wxSysDictService.getDictLabel(needInfo.getType(), "need_type", needInfo.getType());
        needInfo.setTypeLabel(typeLable);
    }
    //设置地区名称
    private void setRegionName(NeedInfo needInfo){
        if (StringUtil.isNotEmpty(needInfo.getCity())) {
            Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getCity()));
            if (r != null)
                needInfo.setCityLabel(r.getName());
        }
        if (StringUtil.isNotEmpty(needInfo.getProvince())) {
            Region r = regionService.selectByPrimaryKey(Integer.parseInt(needInfo.getProvince()));
            if (r != null)
                needInfo.setProvinceLabel(r.getName());
        }
    }
    //设置用户名
    private void setUserName(NeedInfo needInfo){
        UserInfo userInfo = userInfoService.selectUserInfoByid(needInfo.getUserInfoId().intValue());
        if (userInfo != null) {
            if ("1".equals(userInfo.getType()))
                needInfo.setUserName(userInfo.getRealName());
            if ("2".equals(userInfo.getType())) {
                UserInforCompany userInforCompany = userInfoService.selectUserInfoCompanyById(userInfo.getUserId());
                if (userInforCompany != null)
                    needInfo.setUserName(userInforCompany.getCompanyName());
            }
        }
    }
    private void setApprovalUserName(NeedInfo needInfo){
        if(needInfo.getApprovalBy()!=null){
            SysUserEntity entity = sysUserService.getById(needInfo.getApprovalBy());
            if(entity!=null){
                needInfo.setApprovalUserName(entity.getUsername());
            }
        }
    }
}
